package cn.com.woxitech.dev.common;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.fasterxml.jackson.databind.JsonNode;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

import cn.com.woxitech.dev.model.QiniuUploadResult;

public class QiniuPhotoUploadUtils {
	
	public  static  QiniuUploadResult upload(String key, String targetKey, String imgurlbase,String imageFormat, String sourceBucket, String targetBucket) {
	

		Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
		
		String imgurl = imgurlbase +"/"+ key;
		imgurl = imgurl + "?"+imageFormat;
		String targetIcon = targetKey;


		OperationManager operater = new OperationManager(auth);


		String notifyURL = "";
		boolean force = true;
		String pipeline = "PPTToJPG";

		StringMap params = new StringMap().putNotEmpty("notifyURL", notifyURL)
		        .putWhen("force", 1, force).putNotEmpty("pipeline", pipeline);

		String fops = imageFormat;
		fops += "|saveas/" + UrlSafeBase64.encodeToString(targetBucket + ":" + targetIcon);
		
		String prefopUrl = "";
		
		try {
	        // 针对指定空间的文件触发 pfop 操作
	        String id = operater.pfop(sourceBucket, key, fops, params);
	        // 可通过下列地址查看处理状态信息。
	        // 实际项目中设置 notifyURL，接受通知。通知内容和处理完成后的查看信息一致。
	        prefopUrl = "http://api.qiniu.com/status/get/prefop?id=" + id;
	    } catch (QiniuException e) {
	        Response r = e.response;
	        // 请求失败时简单状态信息
	        System.out.println(r.toString());
	        try {
	            // 响应的文本信息
	        	System.out.println(r.bodyString());
	        } catch (QiniuException e1) {
	            //ignore
	        }
	    }
		
		
		return new QiniuUploadResult(prefopUrl, Const.QINIU_BASE_URL+"/"+ targetIcon);
	}

	public static String pagecountPfop( String key, String bucket) {
		// TODO Auto-generated method stub
		Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
		OperationManager operater = new OperationManager(auth);
		String pipeline = "PPTToJPG";
		StringMap params = new StringMap().putNotEmpty("pipeline", pipeline);
		String fops = "yifangyun_preview/v2/action=get_page_count";
		String urlbase64 = UrlSafeBase64.encodeToString(bucket+":"+key+"_count");
		String pfops = fops + "|saveas/"+urlbase64;
		String pid = null;
		try {
			pid = operater.pfop(bucket, key, pfops, params);
	        // 可通过下列地址查看处理状态信息。
	        // 实际项目中设置 notifyURL，接受通知。通知内容和处理完成后的查看信息一致。
	        //String url = "http://api.qiniu.com/status/get/prefop?id=" + id;
	    } catch (QiniuException e) {
	        Response r = e.response;
	        // 请求失败时简单状态信息
	        System.out.println(r.toString());
	        try {
	            // 响应的文本信息
	        	System.out.println(r.bodyString());
	        } catch (QiniuException e1) {
	            //ignore
	        }
	    }
		return pid;
	}

	public static boolean fileExist(String key, String bucket) {
		
		Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
		
	    //实例化一个BucketManager对象
	    BucketManager bucketManager = new BucketManager(auth);
	    //要测试的空间和key，并且这个key在你空间中存在
	    try {
	      //调用stat()方法获取文件的信息
	      FileInfo info = bucketManager.stat(bucket, key);
	      System.out.println(info.hash);
	      System.out.println(info.key);
	      
	      return true;
	    } catch (QiniuException e) {
	      //捕获异常信息
	      Response r = e.response;
	      System.out.println(r.toString());
	    }
		return false;
	}

	public static boolean fileExist(String prefopUrl) throws Exception {
		// TODO Auto-generated method stub
		
		String resp = HttpClientUtils.sendGET(prefopUrl);
		JsonNode _resp = JSONUtils.toJson(resp);
		int code  = _resp.get("code").intValue();
		
		if(code == 1 || code == 0){
			return true;
		}else
			return false;
	}
	
//	public static String getImgurlbase(String bucket){
//		
//		if(bucket.equals(Const.Bucket_WMLOGO)){
//			return "7xstaf.com2.z0.glb.qiniucdn.com";	
//		}else if(bucket.equals(Const.Bucket_WMPPT)){
//			return "7xsvsj.com2.z0.glb.qiniucdn.com";
//		}
//		
//		return "";
//		
//	}
//
//	public static String getppturlbase() {
//		// TODO Auto-generated method stub
//		return "o7tm3334h.bkt.clouddn.com";
//	}
//
//	public static byte[] downloadImg(String urlString) throws IOException {
//		// TODO Auto-generated method stub
//		// 构造URL
//		URL url;
//		byte[] data = null;
//		InputStream is;
//		ByteArrayOutputStream os;
//
//		url = new URL(urlString);
//		// 打开连接
//		URLConnection con = url.openConnection();
//		// 设置请求超时为5s
//		con.setConnectTimeout(5 * 1000);
//		// 输入流
//		is = con.getInputStream();
//
//		// 1K的数据缓冲
//		byte[] bs = new byte[1024];
//		// 读取到的数据长度
//		int len;
//		// 输出的文件流
//		os = new ByteArrayOutputStream();
//		// 开始读取
//		while ((len = is.read(bs)) != -1) {
//			os.write(bs, 0, len);
//		}
//		data = os.toByteArray();
//		// 完毕，关闭所有链接
//		os.close();
//		is.close();
//
//		return data;
//	}
//
//	public static void upload(byte[] data, String targetBucket, String keyname)  throws IOException {
//		// TODO Auto-generated method stub
//		
//		// 密钥配置
//		Auth auth = Auth.create(HJSConstants.ACCESS_KEY, HJSConstants.SECRET_KEY);
//		
//		// 创建上传对象
//		UploadManager uploadManager = new UploadManager();
//		String token =  auth.uploadToken(targetBucket);
//		
//		
//		//调用put方法上传
//	    Response res = uploadManager.put(data, keyname, token);
////	    try{
////	      //打印返回的信息
////	      System.out.println(res.bodyString()); 
////	      } catch (QiniuException e) {
////	          Response r = e.response;
////	          // 请求失败时打印的异常的信息
////	          System.out.println(r.toString());
////	          try {
////	              //响应的文本信息
////	            System.out.println(r.bodyString());
////	          } catch (QiniuException e1) {
////	              //ignore
////	          }
////	      }       
//	}

}
